/**
 * @file date-range
 * @author liaoxuezhi@baidu.com
 */
/* eslint fecs-indent: [0, "space", 2, 2] */
import * as React from 'react';
import {
  PureComponent,
  PropTypes
} from 'react';
import * as cx from 'classnames';
import {findDOMNode} from 'react-dom';
import {
  Editor,
  Html
} from 'slate';

import RULES from './rules';
import schema from './schema';

import '../rich-text.scss';
const serializer = new Html({ rules: RULES });
import Toolbar from './toolbar';
import plugins from './plugins/index.jsx';

export default class RichEditor extends PureComponent
{
  static propTypes = {
    className: PropTypes.string,
    onChange: PropTypes.func.isRequired
  };

  static defaultProps = {
    onChange: value => console.log(value),
    placeholder: '请输入'
  };

  constructor(props) {
    super(props);

    this.state = {
      focus: false,
      state: serializer.deserialize(props.value || '<p></p>')
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleFocus = this.handleFocus.bind(this);
    this.handleBlur = this.handleBlur.bind(this);
  }

  handleChange(state) {
    this.setState({
      state
    });
  }

  handleFocus() {
    this.setState({
      focus: true
    });
    this.refs.editor.focus();
  }

  handleBlur() {
    this.setState({
      focus: false
    });
  }

  render() {
    const {
      className
    } = this.props;

    const {
      focus
    } = this.state;

    return (
      <div className={cx('rich-text-editor', className)}>
        <Toolbar
          state={this.state.state}
          onChange={this.handleChange}
          focusEditor={this.handleFocus}
        />
        <div
          className={cx('rich-text-editor-inner form-control', {
            focus
          })}
          onClick={this.handleFocus}
        >
          <Editor
            ref="editor"
            schema={schema}
            state={this.state.state}
            plugins={plugins}
            onChange={this.handleChange}
            onBlur={this.handleBlur}
          />
        </div>
      </div>
    );
  }
}